import { loginByUsername, logout, getUserInfo as findUserInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router from "@/router/index";

const user = {
  state: {
    user: {},
    token: getToken(),
    name: '',
    avatar: './static/avatar.jpg',
    introduction: '',
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_USER: (state, user) => {
      state.user = user
    }
  },

  actions: {
    // 用户名登录
    async userLogin({ commit }, userInfo) {
      const username = userInfo.user_name.trim()
      const { data } = await loginByUsername(username, userInfo.passwd);
      commit('SET_TOKEN', data.token)
      localStorage.setItem('userInfo', JSON.stringify(data || {}))
      commit('SET_USER', data)
      setToken(data.token)
    },
    // 登出
    userLogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    async getUserInfo({ commit, state }) {
      const { id, type } = state.user
      const getLocal = localStorage.getItem('userInfo')
      let parseJson = {}
      if (getLocal) parseJson = JSON.parse(getLocal)
      const { id: userId, type: userType } = id ? { id, type } : parseJson
      if (!userId) {
        commit('SET_TOKEN', '')
        removeToken()
        router.push('/login')
        return
      }
      const { data } = await findUserInfo({ userId })
      commit('SET_NAME', data.user_name)
      commit('SET_USER', data)
      // commit('SET_AVATAR', data.avatar)
      // commit('SET_INTRODUCTION', data.introduction)
      return userType === 'admin'
    },
    // 前端 登出
    async fedLogOut({ commit }) {
      commit('SET_TOKEN', '')
      removeToken()
    }
  }
}

export default user
